import sys
import os
import random
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *

class Demo(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)

        toolLayout = QHBoxLayout()
        toolLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        btn = QPushButton('Add')
        btn.clicked.connect(self.OnAddClicked)
        toolLayout.addWidget(btn)

        btn = QPushButton('Insert')
        btn.clicked.connect(self.OnInsertClicked)
        toolLayout.addWidget(btn)

        btn = QPushButton('Delete')
        btn.clicked.connect(self.OnDeleteClicked)
        toolLayout.addWidget(btn)

        layout.addLayout(toolLayout)
        self.tabwidget = QTabWidget()
        self.tabwidget.setTabsClosable(True)#可关闭
        self.tabwidget.currentChanged.connect(self.CurrentChanged)
        self.tabwidget.tabCloseRequested.connect(self.TabCloseRequested)
        layout.addWidget(self.tabwidget)

        self.setLayout(layout) 
    def OnAddClicked(self):
        widgetName = f'Page{self.tabwidget.count()}'
        self.tabwidget.addTab(QWidget(),widgetName)
        self.parent.OnShowMessage(f"Add Page:{widgetName}")
    def OnInsertClicked(self):
        widgetName = f'Page{self.tabwidget.count()}'
        index = self.tabwidget.currentIndex()
        if index==-1:
            index=0
        self.tabwidget.insertTab(index,QWidget(),widgetName)
        self.parent.OnShowMessage(f"Insert Page:{widgetName}")
    def OnDeleteClicked(self):
        currentIndex = self.tabwidget.currentIndex()
        if currentIndex==-1:return
        currentName = self.tabwidget.tabText(currentIndex)
        self.parent.OnShowMessage(f"Delete Page:{currentName}")
        self.tabwidget.removeTab(currentIndex)
    def CurrentChanged(self,index):
        currentName = self.tabwidget.tabText(index)
        self.parent.OnShowMessage(f"Current Page:{currentName}")
    def TabCloseRequested(self,index):
        currentName = self.tabwidget.tabText(index)
        self.parent.OnShowMessage(f"Close Page:{currentName}")
        self.tabwidget.removeTab(index)
def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet